<template>
  <van-field
    clearable
    label-width="100"
    v-bind="$attrs"
    v-on="$listeners"
    :value="value"
    :input-align="inputAlign"
    :placeholder="$attrs.placeholder || placeholder"
    @keyup.13="onEnter"
  >
    <template #button>
      <slot name="button" />
    </template>
  </van-field>
</template>

<script>
import _ from 'lodash';

export default {
  name: 'qt-input',

  props: {
    value: [String, Number],

    fieldName: {
      type: String,
      required: true,
    },

    inputAlign: {
      type: String,
      default: 'right',
    },

    isScan: {
      type: Boolean,
      default: false,
    },
  },

  computed: {
    placeholder() {
      let text = '';

      if (this.rightIcon !== 'arrow') {
        text = '请输入';
      } else {
        text = '请选择';
      }

      return text + this.$attrs.label;
    },
  },

  created() {
    this.$listeners.click = this.click;
  },

  methods: {
    click: _.debounce(
      function (event) {
        this.$emit('click', event);
      },
      500,
      {
        leading: true,
        trailing: false,
      },
    ),

    onEnter: _.debounce(
      function () {
        if (this.$parent?.$options.name === 'qt-form') {
          this.$parent.validateField([this.$attrs.name]);
        }
      },
      500,
      {
        leading: true,
        trailing: false,
      },
    ),

    handleChange(value) {
      this.$emit('input', value, this.fieldName);
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep {
  .van-field__control:disabled {
    color: #323233;
    -webkit-text-fill-color: #323233;
  }
  .van-field__control::-webkit-input-placeholder {
    color: #96979a;
    -webkit-text-fill-color: #96979a;
  }
}
</style>
